﻿using System;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Windows.Forms;

namespace MainForm
{
    public partial class TimeEdior : Form
    {
        GameEvents gameEvents = null;
        string filePath = string.Empty;
        BindingList<GameEvent> bindGameEvents = null;
        public TimeEdior(string filePath, GameEvents events)
        {
            InitializeComponent();
            this.filePath = filePath;
            this.gameEvents = events == null ? new GameEvents() : events;
            this.lb_Events.DataSource = this.bindGameEvents = new BindingList<GameEvent>(this.gameEvents.Events);
            this.Shown += (s, args) =>
            {
                this.lb_Events.TopIndex = this.lb_Events.Items.Count - (int)(this.lb_Events.Height / this.lb_Events.ItemHeight);
            };
            if (events != null)
            {
                txb_FileName.Text = events.Name;
            }
        }

        private void textBox2_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar != '\b')//允许输入退格键  
            {
                if ((e.KeyChar < '0') || (e.KeyChar > '9'))//允许输入0-9数字  
                {
                    e.Handled = true;
                }
            }
        }

        private void btn_AddEvent_Click(object sender, EventArgs e)
        {
            int timeMin, timeSec, timeMil;
            if (!int.TryParse(txb_EventTimeMin.Text, out timeMin) || !int.TryParse(txb_EventTimeSec.Text, out timeSec) || !int.TryParse(txb_EventTimeMil.Text, out timeMil))
            {
                MessageBox.Show("时间只能是数字！", "悟空你又调皮了", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                return;
            }
            if (txb_EventName.Text.Length < 1)
            {
                MessageBox.Show("请输入事件名称！", "悟空你又调皮了", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                return;
            }
            if (btn_AddEvent.Tag.ToString() == "Add")
            {
                var ts = Convert.ToInt32(new TimeSpan(0, 0, timeMin, timeSec, timeMil).TotalMilliseconds);
                var item = new GameEvent()
                {
                    EventName = txb_EventName.Text,
                    TimeMilliSecond = ts
                };
                if (this.bindGameEvents == null || this.bindGameEvents.Count == 0)
                {
                    this.bindGameEvents.Add(item);
                }
                else
                {
                    var lastItem = this.bindGameEvents.Where(g => g.TimeMilliSecond <= ts).OrderBy(g => g.TimeMilliSecond).Last();
                    var index = this.bindGameEvents.IndexOf(lastItem);
                    this.bindGameEvents.Insert(index + 1, item);
                    this.lb_Events.SelectedItem = item;
                    this.lb_Events.TopIndex = index + 1;
                }
            }
            else if (btn_AddEvent.Tag.ToString() == "Edit")
            {
                var selectItem = (GameEvent)lb_Events.SelectedItem;
                var index = bindGameEvents.IndexOf(selectItem);
                if (selectItem != null)
                {
                    selectItem.TimeMilliSecond = Convert.ToInt32(new TimeSpan(0, 0, timeMin, timeSec, timeMil).TotalMilliseconds);
                    selectItem.EventName = txb_EventName.Text;
                    bindGameEvents[index] = selectItem;
                    bindGameEvents = new BindingList<GameEvent>(bindGameEvents.OrderBy(g => g.TimeMilliSecond).ToList());
                    this.lb_Events.DataSource = bindGameEvents;
                    this.lb_Events.SelectedItem = selectItem;
                }
                btn_AddEvent.Tag = "Add";
                btn_AddEvent.Text = "<<< 添加事件";
                txb_EventTimeMin.Text = txb_EventTimeSec.Text = txb_EventTimeMil.Text = "0";
                MessageBox.Show("修改事件数据成功", "", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                this.lb_Events.TopIndex = this.lb_Events.Items.Count - (int)(this.lb_Events.Height / this.lb_Events.ItemHeight);
            }
            txb_EventName.Clear();
        }

        private void 删除ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var selectItem = lb_Events.SelectedItem;
            if (selectItem != null)
            {
                if (MessageBox.Show("确定删除该事件？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
                {
                    this.bindGameEvents.Remove((GameEvent)selectItem);
                }
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            this.gameEvents = new GameEvents
            {
                Name = txb_FileName.Text,
                Events = new System.Collections.Generic.List<GameEvent>(this.bindGameEvents)
            };
            if (string.IsNullOrEmpty(this.gameEvents.Name))
            {
                MessageBox.Show("还没有输入名称，快起个名字吧~", "悟空你又调皮了", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                return;
            }
            if (string.IsNullOrEmpty(this.filePath))
            {
                this.filePath = Path.Combine(Application.StartupPath, this.txb_FileName.Text + ".timedata");
            }
            this.gameEvents.Events = this.gameEvents.Events.OrderBy(g => g.TimeMilliSecond).ToList();
            this.gameEvents.Save(this.filePath);
            MessageBox.Show("保存成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
        }

        private void btnSaveAs_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
            var result = folderBrowserDialog.ShowDialog();
            if (result != DialogResult.Cancel)
            {
                var path = Path.Combine(folderBrowserDialog.SelectedPath, this.txb_FileName.Text + ".timedata");
                this.gameEvents.Events = this.gameEvents.Events.OrderBy(g => g.TimeMilliSecond).ToList();
                this.gameEvents.Save(path);
                MessageBox.Show("保存成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }
        }

        private void lb_Events_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                var selectItem = (GameEvent)lb_Events.SelectedItem;
                if (selectItem != null)
                {
                    var ts = new TimeSpan(selectItem.TimeMilliSecond * 10000);
                    txb_EventTimeMin.Text = ts.Minutes.ToString();
                    txb_EventTimeSec.Text = ts.Seconds.ToString();
                    txb_EventTimeMil.Text = ts.Milliseconds.ToString();
                    txb_EventName.Text = selectItem.EventName;
                    btn_AddEvent.Text = "<<< 保存修改";
                    btn_AddEvent.Tag = "Edit";
                }
            }
        }
    }
}